package qlsl.androiddesign.api.application;

import android.app.Application;
import android.os.Bundle;
import android.os.Handler;

import com.squareup.leakcanary.LeakCanary;

import org.apache.log4j.Level;

import de.mindpipe.android.logging.log4j.LogConfigurator;
import qlsl.androiddesign.api.handler.CrashHandler;
import qlsl.androiddesign.api.util.commonutil.Log;
import qlsl.androiddesign.api.util.commonutil.ToastUtils;

/**
 * 作者：郑朝军 on 2017/3/17 16:48
 * 邮箱：1250393285@qq.com
 * 公司：武汉润丰壹网信息科技有限公司
 */
public class SoftwareApplication extends Application
{
    /**
     * 单例，耗资源
     */
    private static SoftwareApplication application;
    /**
     * 传值，为短生命周期的一次性变量<br/>
     * 生命周期在[传递，接收]之间，接收后销毁(NULL)<br/>
     * 长生命周期的共享变量请另行定义，本变量不用作共享功能<br/>
     * 用处：从较远的activity跨级返回到某个activity时用<br/>
     * 使用自定义栈中的跨级传值效果相同，但不需销毁<br/>
     */
    private Bundle bundle;
    /**
     * 当前进程ID
     */
    private static int mainThreadId;

    private static Handler handler;

    public void onLowMemory()
    {
        super.onLowMemory();
        System.gc();
    }

    public void onCreate()
    {
        super.onCreate();
        initInstance();
        initCrashHandler();
        initLeakCanary();
        initLog4j();
        initUtil();
    }

    private void initInstance()
    {
        application = this;
    }


    private void initCrashHandler()
    {
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this);
        crashHandler.sendPreviousReportsToServer();
    }

    public static SoftwareApplication getInstance()
    {
        return application;
    }

    private void initLeakCanary()
    {
        if (Log.isDebug)
            LeakCanary.install(this);
    }

    private void initLog4j()
    {
        if (!Log.isDebug)
            return;
        String path = Log.getLogPath(this);
        LogConfigurator logConfigurator = new LogConfigurator();
        logConfigurator.setFileName(path);
        logConfigurator.setRootLevel(Level.DEBUG);
        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
        logConfigurator.setMaxFileSize(1024 * 1024 * 5);
        logConfigurator.setImmediateFlush(true);
        logConfigurator.configure();

        Log.notifyDataSetChanged(this);
    }

    private void initUtil()
    {
        ToastUtils.register(this);
        mainThreadId = android.os.Process.myTid();
        handler = new Handler();
    }

    public Bundle getBundle()
    {
        return bundle;
    }

    public void setBundle(Bundle bundle)
    {
        this.bundle = bundle;
    }

    public static int getMainThreadId()
    {
        return mainThreadId;
    }

    public static Handler getHandler()
    {
        return handler;
    }
}
